package fileexplorer.view;

import fileexplorer.model.Leaf;
import fileexplorer.util.Invoker;
import fileexplorer.util.OSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.event.ActionEvent;

/**
 * Created with IntelliJ IDEA.
 * User: rejeev
 * Date: 4/29/13
 * Time: 9:03 PM
 * To change this template use File | Settings | File Templates.
 */
public class TablePopupMenu extends JPopupMenu {
    private static final Logger LOGGER = LoggerFactory.getLogger(TablePopupMenu.class);
    private FileTable fileTable;

    public TablePopupMenu(FileTable table){
        this.fileTable = table;
        initialize();
    }

    private void initialize(){
        JMenuItem item1 = new JMenuItem("Open In gedit");
        this.add(item1);
        item1.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                int selectedRow = fileTable.getSelectedRow();
                TablePopupMenu.this.openFile(selectedRow, "gedit");
            }
        });

        JMenuItem item2 = new JMenuItem("Open in Firefox");
        this.add(item2);
        item2.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                int selectedRow = fileTable.getSelectedRow();
                TablePopupMenu.this.openFile(selectedRow, "firefox");
            }
        });

        JMenuItem item3 = new JMenuItem("Open in evince");
        this.add(item3);
        item3.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                int selectedRow = fileTable.getSelectedRow();
                TablePopupMenu.this.openFile(selectedRow, "evince");
            }
        });

        JMenuItem item4 = new JMenuItem("Open Terminal");
        this.add(item4);
        item4.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                String terminal = new OSUtil().getTerminalName();
                String workingDirOption = new OSUtil().getWorkingDirOptionName();
                Invoker.invoke(workingDirOption + fileTable.getPath(), terminal);
            }
        });
    }

    private void openFile(int selectedRow, String program){
        Leaf leaf = (Leaf)fileTable.getValueAt(selectedRow, 0);
        String path = leaf.path;
        LOGGER.debug("invoking " + path + " with " + program);
        Invoker.invoke(path, program);
    }
}
